let data = {}

export function showWarningModal ({ title = '提示', content, showCancel = false }) {
  return new Promise((resolve, reject) => {
    wx.showModal({
      title,
      content,
      showCancel,
      success (res) {
        resolve(res)
      }
    })
  })
}

export function setData (key, value) {
  data[key] = value
}

export function getData (key) {
  return data[key]
}

export function http ({
  url,
  data = {},
  method = 'POST',
  loading = true,
  errorDialog = true
}) {
  return new Promise((resolve, reject) => {
    if (!url) {
      reject(new Error('no url'))
      return
    }

    if (loading) {
      wx.showLoading({ title: '加载中', })
      wx.showNavigationBarLoading()
    }

    wx.request({
      url: url,
      method,
      data,
      success: function (res) {
        if (loading) {
          wx.hideLoading()
          wx.hideNavigationBarLoading()
        }


        // 400 500 类似错误
        if (res.statusCode < 200 || res.statusCode > 299) {
          if (errorDialog) {
            showWarningModal({ content: res.statusCode + ' ! ' + (res.data.msg || '') })
          }
          reject(new Error('result false'))
          return
        }

        resolve(res.data)

      },
      fail: function (res) {
        if (loading) {
          wx.hideLoading()
          wx.hideNavigationBarLoading()
        }

        showWarningModal({ content: '网络异常，请稍后再试' })
        reject(new Error(res))
      }
    })
  })
}

export function jsonpToJson (datas, start = 8, end = -2) {
  let jsonData = null
  // 下面是对获取到的数据进行处理，把jsonp格式的数据处理成json格式的数据
  if (typeof datas === 'string') {
    jsonData = datas.slice(start, end)
    if (jsonData) {
      jsonData = JSON.parse(jsonData)
    } else {
      jsonData = {}
    }

  }
  return jsonData
}

let isProductionEnv
export async function env () {
  if (typeof isProductionEnv === 'undefined') {
    let { miniProgram } = wx.getAccountInfoSync()
    let { result } = await wx.cloud.callFunction({
      name: 'getVer'
    })
    isProductionEnv = !!(miniProgram.version && (miniProgram.version != result.ver))
  }
  console.log(isProductionEnv, 'isProductionEnv')
  return !isProductionEnv
}

export function parseTime (time, cFormat) {
  if (time == null) {
    time = Date.now()
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (('' + time).length === 10) time = parseInt(time) * 1000
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const timeStr = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    if (key === 'a') return ['一', '二', '三', '四', '五', '六', '日'][value - 1]
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return timeStr
}

export function clone (data) {
  if (typeof data === 'object') {
    return JSON.parse(JSON.stringify(data))
  }
  return data
}